package org.example.common.aspect;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * FieldError 封装类
 * 将 BindingResult 错误信息转为 map
 *
 * @author Hu Jingling
 * @version 1.0
 * @since 2020-08-03
 */
public class FieldErrorWrapper implements Serializable {

    /**
     * 错误信息
     */
    private Map<String, List<String>> errMsg;

    /**
     * 有参构造
     *
     * @param bindingResult 包含若干属性错误提示信息
     */
    public FieldErrorWrapper(BindingResult bindingResult) {
        errMsg = new LinkedHashMap<>();
        List<ObjectError> errorList = bindingResult.getAllErrors();
        for (ObjectError error : errorList) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                String fieldName = fieldError.getField();
                String fieldMessage = fieldError.getDefaultMessage();
                //list
                List<String> list;
                if (errMsg.get(fieldName) == null) {
                    list = new ArrayList<>();
                } else {
                    list = errMsg.get(fieldName);
                }
                //添加错误信息
                list.add(fieldMessage);
                errMsg.put(fieldName, list);
            }
        }
    }

    public Map<String, List<String>> getErrMsg() {
        return errMsg;
    }

    public void setErrMsg(Map<String, List<String>> errMsg) {
        this.errMsg = errMsg;
    }

    /**
     * 返回错误信息 List
     */
    @Override
    public String toString() {
        return "FieldErrorWrapper{" +
                "errMsg=" + errMsg +
                '}';
    }
}
